/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package SecureUtil;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.util.ArrayList;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;

/**
 *
 * @author Gwang
 */
public class SecureHelper {
    //get password based encryption key
    static SecretKey getPBK(String pswd, Byte salt) throws Exception{
        PBEKeySpec pbeKeySpec;
        //PBEParameterSpec pbeParamSpec;
        SecretKeyFactory keyFac;
        String pwnsalt = pswd+salt.toString();
        pbeKeySpec = new PBEKeySpec(pwnsalt.toCharArray());
        keyFac = SecretKeyFactory.getInstance("PBEWithSHA1AndAES");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
        return pbeKey;
    }

    // get encrypt
    // iv is initial vector it is an output
    static byte[] SymetricEncrypt(SecretKey aesKey, byte[] cleartext, byte[] iv)
            throws Exception{
        // Create PBE Cipher
        Cipher aesCipher = Cipher.getInstance("AES/CBC/ISO10126Padding");

        // Initialize PBE Cipher with key and parameters
        aesCipher.init(Cipher.ENCRYPT_MODE, aesKey);
        // Encrypt the cleartext
        iv = aesCipher.getIV();
        byte[] ciphertext = aesCipher.doFinal(cleartext);
        return ciphertext;
    }

    static byte[] SymetricDecrypt(SecretKey aesKey, byte[] cipher, byte[] iv)
            throws Exception{
        Cipher aesCipher = Cipher.getInstance("AES/CBC/ISO10126Padding");
        // Initialize PBE Cipher with key and parameters
        aesCipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));
        // Encrypt the cleartext
        byte[] plaintext = aesCipher.doFinal(cipher);
        return plaintext;
    }
}
